const validate = require("../middleware/validator");
const { body} = require('express-validator');
const {User}=require('../model')
const md5=require("../util/md5")

exports.register =validate([
  body("user.username").notEmpty().withMessage("用户名不能为空"),
  body("user.password").notEmpty().withMessage("密码不能为空"),
  body("user.email")
    .notEmpty()
    .withMessage("邮箱不能为空")
    .bail()
    .custom(async (email) => {
      const user = await User.findOne({ email }).select('password') ;
      if (user) {
        return Promise.reject("邮箱已经注册了");
      }
    })    

])

 exports.login=[
      validate([
     body("user.email").notEmpty().withMessage("邮箱不能为空"),
     body("user.password").notEmpty().withMessage("密码不能为空"),
     ]), 
  
 validate([
  body("user.email").custom(async (email,{req})=>{
    const user= await User.findOne({email}).select(['password','username','email','image','bio'])
    // console.log(user)
    if(!user){
      return Promise.reject('用户未注册')
    }
    req.user=user
  })
 ]),
 validate([
  body("user.password").custom(async (password,{req})=>{
    console.log(req.user)
    //  console.log(md5(password))
    //  console.log(req.user.pasword)
     if(md5(password) !==req.user.password){
       return Promise.reject("密码错误")
     }
    })
   ])  
]
